//
//  MineViewController.m
//  PTravel
//
//  Created by dllo on 15/11/13.
//  Copyright © 2015年 李涵. All rights reserved.
//

#import "MineViewController.h"
#import "MyDestinationViewController.h"
@interface MineViewController ()<UITableViewDataSource,UITableViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (retain, nonatomic)UITableView *myTableView;
@property (retain, nonatomic)NSMutableArray *textArr;//文字数组
@property (retain, nonatomic)NSMutableArray *imageArr;//图标数组
@property (retain, nonatomic)UIView *backgroundView;//背景view
@property (retain, nonatomic)UIImageView *bgImage;//背景图片
@property (retain, nonatomic)UIImageView *PicImage;//头像
@property (retain, nonatomic)MBProgressHUD *hud1;//菊花
@property (assign, nonatomic)float size;//缓冲文件大小
@property (retain, nonatomic)UISwitch *sw;//夜间模式开关
@property (retain, nonatomic)UIImagePickerController *pick;
@property (retain, nonatomic)UIImagePickerController *pick1;

@end

@implementation MineViewController

- (void)dealloc
{
    [_myTableView release];
    [_textArr release];
    [_imageArr release];
    [_backgroundView release];
    [_bgImage release];
    [_PicImage release];
    [_hud1 release];
    [_sw release];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    
    self.navigationController.navigationBar.translucent = YES;
    UIImage *image = [UIImage imageNamed:@""];
    [self.navigationController.navigationBar setBackgroundImage:image
                                                  forBarMetrics:UIBarMetricsDefault];
    //夜间模式判断
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeColor:) name:@"night" object:nil];
    self.size = [[SDImageCache sharedImageCache] getSize]/1024.0/1024.0;
    [self.myTableView reloadData];
    
}

- (void)changeColor:(NSNotificationCenter *)notification
{
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:TEXTCOLOR};
    self.navigationController.navigationBar.barTintColor = BARCOLOR;
    self.view.backgroundColor = CELLCOLOR;
    self.myTableView.backgroundColor = CELLCOLOR;
    self.backgroundView.backgroundColor = CELLCOLOR;
    self.myTableView.backgroundColor = [Night cellColor];
    [self.myTableView reloadData];
  
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.sw = [[UISwitch alloc]initWithFrame:CGRectMake(BOUNDS.size.width-60*WIDTH, 8*HEGIHT, 80*WIDTH, 32*HEGIHT)];
    [_sw release];
    
    //大的背景view
    self.backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, BOUNDS.size.width, BOUNDS.size.height/3+40*HEGIHT)];
    self.backgroundView.backgroundColor = CELLCOLOR;
    [_backgroundView release];
    
    //小的背景UIImageView
    self.bgImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, BOUNDS.size.width, BOUNDS.size.height/3)];
    self.bgImage.backgroundColor = [UIColor colorWithRed:0.316 green:0.769 blue:0.830 alpha:1.000];
    self.bgImage.image = [UIImage imageNamed:@"mine.jpg"];
    self.bgImage.contentMode = UIViewContentModeScaleAspectFill;
//    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bgAction)];
//    self.bgImage.userInteractionEnabled = YES;
//    [self.bgImage addGestureRecognizer:tap1];
    [self.backgroundView addSubview:self.bgImage];
    [_bgImage release];
    
    //头像
    self.PicImage = [[UIImageView alloc] initWithFrame:CGRectMake(BOUNDS.size.width/2-40*WIDTH, self.backgroundView.frame.size.height-80*HEGIHT, 80*WIDTH, 80*HEGIHT)];
    self.PicImage.backgroundColor = [UIColor colorWithRed:0.135 green:0.830 blue:0.190 alpha:1.000];
    self.PicImage.layer.masksToBounds = YES;
    self.PicImage.layer.cornerRadius = 40;
    self.PicImage.userInteractionEnabled = YES;
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"isExite"] length] == 0) {
        self.PicImage.image = [UIImage imageNamed:@"placeholder.jpg"];
    }else{
        self.PicImage.image = [self getPhotoFromName:@"public.image"];
    }
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(picAction)];
    [self.PicImage addGestureRecognizer:tap];
    [self.backgroundView addSubview:self.PicImage];
    [_PicImage release];
    
    
    self.view.backgroundColor = CELLCOLOR;
    
    //tableview
    self.myTableView = [[UITableView alloc] initWithFrame:BOUNDS style:UITableViewStylePlain];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.backgroundColor = CELLCOLOR;
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.myTableView registerClass:[MineTableViewCell class] forCellReuseIdentifier:@"MineTableViewCell"];
    self.myTableView.tableHeaderView = self.backgroundView;
    [self.view addSubview:self.myTableView];
    self.textArr = [NSMutableArray arrayWithObjects:@"我的折扣", @"我的目的地", @"清理缓存", @"夜间模式", @"关于", nil];
    self.imageArr = [NSMutableArray arrayWithObjects:@"discountPic.png",@"destinationPic.png",@"deleteCaches.png",@"night.png",@"iconfont-guanyuwomen.png", nil];
    [_myTableView release];
    
    self.navigationItem.title = @"我的";
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:TEXTCOLOR};
    self.navigationController.navigationBar.barTintColor = BARCOLOR;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
}

#pragma mark === 将图片存入沙盒
-(BOOL) setPhotoToPath:(UIImage *)image isName:(NSString *)name
{
    //此处首先指定了图片存取路径（默认写到应用程序沙盒 中）
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    
    //并给文件起个文件名
    NSString *uniquePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:name];
    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:uniquePath];
    if (blHave) {
        NSLog(@"already have");
        //delete
        [self deleteFromName:name];
    }
    NSData *data = UIImagePNGRepresentation(image);
    BOOL result = [data writeToFile:uniquePath atomically:YES];
    if (result) {
        //NSLog(@"success");
        return YES;
    }else {
        //NSLog(@"no success");
        return NO;
    }
}
#pragma mark === 根据名字取图片
- (UIImage *)getPhotoFromName:(NSString *)name
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    //NSFileManager* fileManager=[NSFileManager defaultManager];
    NSString *uniquePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:name];
    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:uniquePath];
    if (!blHave) {
        return nil;
    }else
    {
        NSData *data = [NSData dataWithContentsOfFile:uniquePath];
        UIImage *img = [[UIImage alloc] initWithData:data];
        // NSLog(@" have");
        return img;
    }
}
#pragma mark === 根据名字删除
-(BOOL)deleteFromName:(NSString *)name
{
    NSFileManager* fileManager=[NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    //文件名
    NSString *uniquePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:name];
    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:uniquePath];
    if (!blHave) {
        //NSLog(@"no  have");
        return NO;
    }else {
        //NSLog(@" have");
        BOOL blDele= [fileManager removeItemAtPath:uniquePath error:nil];
        if (blDele) {
            //NSLog(@"dele success");
            return YES;
        }else {
            //NSLog(@"dele fail");
            return NO;
        }
    }
}


#pragma mark === 背景点击方法
- (void)bgAction
{
    self.pick = [[UIImagePickerController alloc] init];
    self.pick.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    self.pick.allowsEditing = YES;
    self.pick.delegate = self;
    [self presentViewController:self.pick animated:YES completion:^{
        
    }];
}

#pragma mark === 头像点击方法
- (void)picAction
{
    self.pick1 = [[UIImagePickerController alloc] init];
    self.pick1.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    self.pick1.allowsEditing = YES;
    self.pick1.delegate = self;
    [self presentViewController:self.pick1 animated:YES completion:^{
        
    }];
}
#pragma mark === 进入相册方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"isExite"] isEqualToString:@"YES"])
    {
        
        [[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"%d",![self deleteFromName:@"public.image"]] forKey:@"isExite"];
    }
    NSLog(@"info = %@",info);//打印是一个字典
    //根据字典中key为UIImagePickerControllerOriginalImage来获取图片
    UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

    self.PicImage.image = image;
    [[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"%d",[self setPhotoToPath:image isName:@"public.image"]] forKey:@"isExite"];
    
    
    [picker dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.textArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MineTableViewCell" forIndexPath:indexPath];
    cell.backgroundColor = [Night cellColor];
    cell.label.text = [self.textArr objectAtIndex:indexPath.row];
    cell.image.image = [UIImage imageNamed:[self.imageArr objectAtIndex:indexPath.row]];
    if (indexPath.row == 2) {
        if (self.size != 0) {
            cell.label.text = [NSString stringWithFormat:@"%@ (您有%.2fMB垃圾)",[self.textArr objectAtIndex:indexPath.row],self.size];
        }else{
            cell.label.text = [self.textArr objectAtIndex:indexPath.row];
        }
    }else if (indexPath.row == 3) {
        
        NSString *str = [[NSUserDefaults standardUserDefaults] objectForKey:@"states"];
        if ([str isEqualToString:@"1"]) {
            [self.sw setOn:YES];
        }else{
            [self.sw setOn:NO];
        }
        [self.sw addTarget:self action:@selector(switchAction) forControlEvents:UIControlEventValueChanged];
        [cell addSubview:self.sw];
        
    }else if (indexPath.row == 4){
        
    }else{
        //设置右边的小图标
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark === switch夜间模式
- (void)switchAction
{
    //把states状态给string,未设置之前为0
    NSString *string = [[NSUserDefaults standardUserDefaults] objectForKey:@"states"];
    if ([string isEqualToString:@"1"]) {
        [self.sw setOn:YES];
        //存状态
        [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"states"];
        //说明要打开夜间模式(post发送通知)
        [[NSNotificationCenter defaultCenter] postNotificationName:@"night" object:[UIColor blackColor]];
    }else{
        [self.sw setOn:NO];
        //NSUserDefault    变为  0
        //他是为了永久改变,下次重新启动时
        [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"states"];
        
        //但是变色是用通知改变的
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"night" object:[UIColor greenColor]];
        
        
    }
}
#pragma mark === tableView方法点击
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        MyDiscountViewController *dis = [[MyDiscountViewController alloc] init];
        [self.navigationController pushViewController:dis animated:YES];

    }
    if (indexPath.row == 1) {
        MyDestinationViewController *dis = [[MyDestinationViewController alloc] init];
        [self.navigationController pushViewController:dis animated:YES];
    }
    if (indexPath.row == 2){
        
        
        self.hud1 = [[MBProgressHUD alloc] initWithView:self.view];
        self.hud1.dimBackground = YES;
        //设置对话框文字
        NSLog(@"%f",self.size);
        if (self.size != 0) {
            
            self.hud1.labelText = [NSString stringWithFormat:@"%.2fMB垃圾清理中...",self.size];
            self.hud1.mode = MBProgressHUDModeDeterminateHorizontalBar;
            [self.hud1 showWhileExecuting:@selector(myProgressTask) onTarget:self withObject:nil animated:YES];
            
             [[SDImageCache sharedImageCache] clearDisk];
            self.size = 0;
            [self.myTableView reloadData];
            self.hud1.minShowTime = 3;
            
        } else {
            self.hud1.mode = MBProgressHUDModeText;
            self.hud1.labelText = @"缓存好干净,过会再来吧~";
            self.hud1.minShowTime = 1;
        }
        
        [self.view addSubview:self.hud1];
       
    }
    if (indexPath.row == 4) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"版本" message:@"您当前所使用版本为1.0" preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        [self dismissViewControllerAnimated:YES completion:^{
            
            
        }];
    }


}
- (void)myProgressTask {
    // This just increases the progress indicator in a loop
    float progress = 0.0f;
    while (progress < 1.0f) {
        progress += 0.01f;
        self.hud1.progress = progress;
        usleep(30000);
    }
}

#pragma mark === 下拉变大
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //刚开始y的偏移量初始值就是-264
    CGFloat y = scrollView.contentOffset.y + 64;//加上导航栏高度,第一次是-200
    
    
    if (y < 0) {
        CGRect frame = self.bgImage.frame;
        frame.origin.y = y;//偏移了多少,
        frame.size.height = 200*HEGIHT -y;//tablview向下偏移了多少,高度就是多少
        self.bgImage.frame = frame;
    }
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
